package utils

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"go_code/project01_basic/chapter15_qq/message"
	"net"
)

type Transfer struct {
	Conn net.Conn
	Buf  [8192]byte
}

func (t *Transfer) Delivery(mes *message.Message) (err error) {
	data, err := json.Marshal(mes)
	if err != nil {
		fmt.Println("json.Marshal err=", err)
		return
	}

	//发送消息长度,将int长度转换成byte切片显示
	pkgLen := uint64(len(data))
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf[:8], pkgLen)

	_, err = t.Conn.Write(buf)
	if err != nil {
		fmt.Println("conn.Write err =", err)
		return
	}

	//发送消息内容
	n, err := t.Conn.Write(data)
	if err != nil {
		fmt.Println(n, ",conn.Write err =", err)
		return
	}
	return
}

func (t *Transfer) ReadPkg() (mes *message.Message, err error) {
	buf := make([]byte, 8192)
	_, err = t.Conn.Read(buf[:8])
	if err != nil {
		return
	}
	pkgLen := binary.BigEndian.Uint64(buf[:8])
	n, err := t.Conn.Read(buf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		return
	}
	mes = new(message.Message)
	err = json.Unmarshal(buf[:pkgLen], mes)
	return
}
